import {Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef} from '@angular/core';
import {NbLoginComponent} from '@nebular/auth';
import {SERVER_URL} from '../config';
import {Router, ActivatedRoute} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {NbAuthService} from '@nebular/auth';
import {NbToastrService} from '@nebular/theme';
import {NbToastStatus} from '@nebular/theme/components/toastr/model';

export interface ReturnData {
  ret: number;
  data: any;
  msg: string;
}

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})

export class LoginComponent extends NbLoginComponent {
  constructor(private http: HttpClient,
              private activatedRoute: ActivatedRoute,
              private toastrService: NbToastrService,
              protected service: NbAuthService,
              protected cd: ChangeDetectorRef,
              protected router: Router) {
    super(service, {}, cd, router);
    activatedRoute.queryParams.subscribe(queryParams => {
      const action = queryParams.action;
      if (action === 'logout') {
        sessionStorage.removeItem('token');
        sessionStorage.removeItem('account');
        sessionStorage.removeItem('account');
      }
    });
  }

  login() {
    this.errors = [];
    this.messages = [];
    this.submitted = true;
    const formData = new FormData();
    formData.append('Account', this.user.account);
    formData.append('Auth', this.user.auth);
    formData.append('Password', this.user.password);
    this.http.post(SERVER_URL + '?s=App.Fcpn.Login', formData).subscribe((data: ReturnData) => {
        this.submitted = false;
        if (data.data !== false) {
          this.toastrService.show('登录成功', '提示', {status: NbToastStatus.SUCCESS});
          sessionStorage.setItem('token', data.data);
          sessionStorage.setItem('role', this.user.auth);
          sessionStorage.setItem('account', this.user.account);
          if (this.user.auth === '2') {
            this.router.navigate(['/company/dashboard']);
          } else if(this.user.auth === '1') {
            this.router.navigate(['/admin/dashboard']);
          }
        } else {
          this.toastrService.show('用户名密码或身份错误', '提示', {status: NbToastStatus.DANGER});
        }
      },
      (error) => {
        this.toastrService.show(error, '提示', {status: NbToastStatus.DANGER});
      });

  }
}


